-- character_manager.lua
-- 角色管理器：负责创建和管理游戏中的角色

local CharacterManager = {}
CharacterManager.__index = CharacterManager

function CharacterManager.new()
    return setmetatable({
        characters = {},
        healthSystem = nil  -- 添加血量系统引用
    }, CharacterManager)
end

-- 设置血量系统
function CharacterManager:setHealthSystem(healthSystem)
    self.healthSystem = healthSystem
    print("血量系统已设置到角色管理器")
end

-- 创建角色（支持玩家和NPC）
function CharacterManager:createCharacter(id, position, movementSystem, options)
    options = options or {}
    
    local Node = require("Node")
    local Vec2 = require("Vec2")
    
    local characterNode = Node()
    characterNode.position = Vec2(position.x, position.y)
    
    local entityData = {
        id = id,
        position = {x = position.x, y = position.y},
        velocity = {x = 0, y = 0},
        maxSpeed = options.maxSpeed or 800,
        mass = options.mass or 1,
        node = characterNode,
        radius = options.radius or 25,
        health = options.health or 100,  -- 添加血量属性
        maxHealth = options.maxHealth or 100,
        isEnemy = options.isEnemy or false  -- 保留isEnemy字段，但不会用于敌人功能
    }
    
    local entity = movementSystem:registerEntity(entityData)
    
    local character = {
        node = characterNode,
        entity = entity,
        entityData = entityData,
        id = id,
        spineNode = nil,
        healthBar = nil,  -- 血条引用
        isEnemy = options.isEnemy or false,
        health = entityData.health,
        maxHealth = entityData.maxHealth
    }
    
    self.characters[id] = character
    
    print("角色创建成功: " .. id .. " 位置: (" .. position.x .. ", " .. position.y .. ") 血量: " .. character.health .. "/" .. character.maxHealth)
    
    -- 创建血条（玩家显示血条）
    if id == "player" then
        self:createHealthBarForCharacter(id, options)
    end
    
    return characterNode, entity, character
end

-- 为角色创建血条
function CharacterManager:createHealthBarForCharacter(characterId, options)
    if not self.healthSystem then
        print("警告：血量系统未设置，无法为 " .. characterId .. " 创建血条")
        return nil
    end
    
    local character = self.characters[characterId]
    if not character then
        print("错误：找不到角色 " .. characterId)
        return nil
    end
    
    -- 配置血条选项
    local healthBarOptions = options.healthBarOptions or {}
    
    -- 设置血条选项
    healthBarOptions.width = healthBarOptions.width or 200
    healthBarOptions.height = healthBarOptions.height or 24
    healthBarOptions.offsetY = healthBarOptions.offsetY or 80
    
    -- 创建血条
    local healthBar = self.healthSystem:createHealthBar(characterId, healthBarOptions)
    if not healthBar then
        print("创建血条失败: " .. characterId)
        return nil
    end
    
    -- 设置血条跟随目标
    local success = self.healthSystem:setHealthBarTarget(characterId, character.node, 0, healthBarOptions.offsetY or 80)
    if success then
        character.healthBar = healthBar
        print("血条已添加到角色: " .. characterId)
    else
        print("设置血条目标失败: " .. characterId)
    end
    
    return healthBar
end

-- 更新角色血量
function CharacterManager:updateCharacterHealth(characterId, deltaHealth)
    local character = self.characters[characterId]
    if not character then
        print("错误：找不到角色 " .. characterId)
        return false
    end
    
    local newHealth = character.health + deltaHealth
    if newHealth < 0 then newHealth = 0 end
    if newHealth > character.maxHealth then newHealth = character.maxHealth end
    
    character.health = newHealth
    
    -- 更新实体数据
    if character.entity and character.entity.health then
        character.entity.health = newHealth
    end
    
    -- 更新血条
    if character.healthBar then
        character.healthBar:updateHealth(newHealth, character.maxHealth)
    elseif self.healthSystem then
        -- 尝试通过血量系统更新
        self.healthSystem:updateHealthBar(characterId, newHealth, character.maxHealth)
    end
    
    -- 如果血量归零
    if newHealth <= 0 then
        print("角色 " .. characterId .. " 死亡")
        character.isDead = true
    end
    
    return true
end

-- 设置角色血量
function CharacterManager:setCharacterHealth(characterId, health, maxHealth)
    local character = self.characters[characterId]
    if not character then
        print("错误：找不到角色 " .. characterId)
        return false
    end
    
    character.health = health or character.health
    character.maxHealth = maxHealth or character.maxHealth
    
    if character.health < 0 then character.health = 0 end
    if character.maxHealth <= 0 then character.maxHealth = 100 end
    
    -- 更新实体数据
    if character.entity then
        character.entity.health = character.health
        character.entity.maxHealth = character.maxHealth
    end
    
    -- 更新血条
    if character.healthBar then
        character.healthBar:updateHealth(character.health, character.maxHealth)
    elseif self.healthSystem then
        self.healthSystem:updateHealthBar(characterId, character.health, character.maxHealth)
    end
    
    print("角色 " .. characterId .. " 血量设置为: " .. character.health .. "/" .. character.maxHealth)
    return true
end

-- 获取角色血量信息
function CharacterManager:getCharacterHealth(characterId)
    local character = self.characters[characterId]
    if not character then return nil end
    
    return {
        current = character.health,
        max = character.maxHealth,
        isDead = character.health <= 0
    }
end

function CharacterManager:setSpineNode(id, spineNode)
    local character = self.characters[id]
    if character and spineNode then
        character.spineNode = spineNode
        character.node:addChild(spineNode)
        return true
    end
    return false
end

function CharacterManager:getSpineNode(id)
    local character = self.characters[id]
    return character and character.spineNode or nil
end

function CharacterManager:destroyCharacter(id)
    local character = self.characters[id]
    if character then
        -- 清理血条
        if character.healthBar then
            character.healthBar:cleanup()
        end
        
        -- 清理Spine节点
        if character.spineNode and character.spineNode.parent then
            character.spineNode:removeFromParent()
        end
        
        -- 清理节点
        if character.node and character.node.parent then
            character.node:removeFromParent()
        end
        
        -- 从血量系统移除
        if self.healthSystem and self.healthSystem.healthBars then
            self.healthSystem.healthBars[id] = nil
        end
        
        self.characters[id] = nil
        print("角色销毁: " .. id)
        return true
    end
    return false
end

function CharacterManager:getCharacter(id)
    return self.characters[id]
end

-- 获取所有角色ID
function CharacterManager:getAllCharacterIds(filter)
    local ids = {}
    for id, character in pairs(self.characters) do
        if not filter or 
           (filter == "player" and id == "player") or
           (filter == "npc" and not character.isEnemy and id ~= "player") then
            table.insert(ids, id)
        end
    end
    return ids
end

function CharacterManager:getCharacterNode(id)
    local character = self.characters[id]
    return character and character.node or nil
end

function CharacterManager:getCharacterEntity(id)
    local character = self.characters[id]
    return character and character.entity or nil
end

function CharacterManager:setCharacterPosition(id, x, y)
    local character = self.characters[id]
    if character and character.entity then
        character.entity.position.x = x
        character.entity.position.y = y
        
        if character.node then
            character.node.x = x
            character.node.y = y
        end
        return true
    end
    return false
end

function CharacterManager:addAllCharactersToScene(scene)
    local count = 0
    for id, character in pairs(self.characters) do
        if character.node and not character.node.parent then
            scene:addChild(character.node)
            count = count + 1
            print("角色添加到场景: " .. id)
        end
    end
    print("总共添加 " .. count .. " 个角色到场景")
end

function CharacterManager:removeAllCharactersFromScene()
    local count = 0
    for id, character in pairs(self.characters) do
        if character.node and character.node.parent then
            character.node:removeFromParent()
            count = count + 1
        end
    end
    print("从场景移除 " .. count .. " 个角色")
end

function CharacterManager:getCharacterCount(filter)
    if not filter then
        local count = 0
        for _ in pairs(self.characters) do
            count = count + 1
        end
        return count
    else
        return #self:getAllCharacterIds(filter)
    end
end

-- 重置
function CharacterManager:reset()
    -- 清理所有血条
    for id, character in pairs(self.characters) do
        if character.healthBar then
            character.healthBar:cleanup()
        end
    end
    
    self:removeAllCharactersFromScene()
    self.characters = {}
    
    -- 清理血量系统引用
    if self.healthSystem then
        self.healthSystem:reset()
    end
    
    print("角色管理器已重置")
end

-- 更新角色管理器
function CharacterManager:update(dt)
    -- 这里可以添加每帧更新的逻辑
    -- 例如：更新血条位置，检查角色状态等
end

return CharacterManager